import java.util.*;


public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }
    public  int i = 0;
    public  TreeNode createTree(String str) {
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        return root;
    }


    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    public void preOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }



    //遍历思路
    List<Character> list = new ArrayList<>();
    public List<Character> preorderTraversal(TreeNode root) {
        if(root == null) return list;
        //System.out.print(root.val+" ");
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }

    //子问题
    public List<Character> preorderTraversal2(TreeNode root) {

        List<Character> list = new ArrayList<>();
        if(root == null) return list;
        list.add(root.val);

        List<Character> leftTree = preorderTraversal2(root.left);
        list.addAll(leftTree);

        List<Character> rightTree = preorderTraversal2(root.right);
        list.addAll(rightTree);

        return list;
    }

    // 中序遍历
    public void inOrder(TreeNode root) {
        if(root == null) return;
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }


    public void inOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");

            cur = top.right;
        }
    }




    // 后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    public void postOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                System.out.print(top.val + " ");
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
    }

    public static int nodeSize = 0;
    // 获取树中节点的个数
    public void size(TreeNode root) {
        if(root == null) {
            return ;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    public int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size2(root.left) +
                size2(root.right)+1;
    }

    /**
     * 获取叶子节点的个数
     *  什么是叶子
     * @param root
     * @return
     */
    public static int leafSize;
    public void getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return;
        }

        if(root.left == null && root.right == null) {
            leafSize++;
        }

        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) +
                getLeafNodeCount2(root.right);
    }
    public int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) +
                getKLevelNodeCount(root.right,k-1);
    }

    /**
     * 时间复杂度：O(N)
     * 空间复杂度：O(logN)
     * @param root
     * @return
     */
    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        //return Math.max(leftHeight,rightHeight)+1;
        return leftHeight >rightHeight
                ? leftHeight+1 : rightHeight+1;
    }

    /**
     * 时间复杂度：O(N)
     * 空间复杂度：O(logN)
     * @param root
     * @param val
     * @return
     */
    public TreeNode findVal(TreeNode root,char val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode leftT = findVal(root.left,val);
        if(leftT != null) {
            return leftT;
        }
        TreeNode rightT = findVal(root.right,val);
        if(rightT != null) {
            return rightT;
        }
        return null;
    }

    /**
     * 假设 p的节点树为m, q的节点树为n
     * 时间复杂度：O(min(m,n))
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //1.先判断结构是否是一样的
        if(p != null && q == null || p == null && q != null) {
            return false;
        }
        //上述if语句 如果没有执行，意味着两个引用 同时为空 或者同时不为空
        if(p == null && q == null) {
            return true;
        }
        //都不为空 判断值是否一样
        if(p.val != q.val) {
            return false;
        }
        //都不为空且值一样
        return isSameTree(p.left,q.left)
                && isSameTree(p.right,q.right);
    }

    /**
     * root共有节点r个，subRoot共有节点s个
     * 时间复杂度：O(r*s)
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) return true;
        if(isSubtree(root.left,subRoot))  return true;
        if(isSubtree(root.right,subRoot))  return true;
        return false;
    }


    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        // if(root.left == null && root.right == null) {
        //     return root;
        // }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree != null && rightTree == null || leftTree == null && rightTree != null) {
            return false;
        }

        if(leftTree == null && rightTree == null) {
            return true;
        }

        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }


    /**
     * 时间复杂度：O(N^2)
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.abs(leftHeight-rightHeight) < 2
                && isBalanced(root.left) && isBalanced(root.right);
    }



    public boolean isBalanced2(TreeNode root) {
        if(root == null) return true;
        return getHeight2(root) >= 0;
    }

    public int getHeight2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight = getHeight2(root.right);
        if(rightHeight >= 0 && Math.abs(leftHeight-rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            return -1;
        }
    }

    TreeNode prev = null;

    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        ConvertChild(pRootOfTree);
        TreeNode head = pRootOfTree;
        while(head.left != null) {
            head = head.left;
        }
        return head;
    }

    public void ConvertChild(TreeNode root) {
        if (root == null) return ;
        ConvertChild(root.left);
        //打印
        root.left = prev;
        if (prev != null) {
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);
    }

    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();//3
            List<Character> list = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                //System.out.print(cur.val + " ");
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }
    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }

        while (!queue.isEmpty()) {
            TreeNode peek = queue.peek();
            if(peek != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }

    public TreeNode lowestCommonAncestor(TreeNode root,  TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        if(root ==p || root == q) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        if(leftTree != null && rightTree != null) {
            return root;
        }else if(leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }

    /**
     *
     * @param root
     * @param node 找的节点
     * @param stack 存储到栈当中
     */
    public boolean getPath(TreeNode root,
                           TreeNode node,
                           Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean ret = getPath(root.left,node,stack);
        if(ret) {
            return true;
        }
        ret = getPath(root.right,node,stack);
        if(ret) {
            return true;
        }
        stack.pop();
        return false;
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        //1.获取路径上的所有节点
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        //2. 比较两个栈的大小，多的出size个
        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if(sizeP > sizeQ) {
            int size = sizeP - sizeQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        }else {
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }
        //3. 每次出数据 看栈顶元素是否一样
        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if (stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            } else {
                stackQ.pop();
                stackP.pop();
            }
        }

        return null;
    }

    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }

        StringBuilder stringBuilder = new  StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();

    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) return;
        stringBuilder.append(t.val);//1

        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }

    }

}














